package com.wangcang.widgetlibrary.activity.wxapi;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.tencent.mm.sdk.constants.ConstantsAPI;
import com.tencent.mm.sdk.modelbase.BaseReq;
import com.tencent.mm.sdk.modelbase.BaseResp;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.IWXAPIEventHandler;
import com.wangcang.widgetlibrary.R;
import com.wangcang.widgetlibrary.bean.PayBean;
import com.wangcang.widgetlibrary.tools.PayUtil;


import java.util.Random;

import static com.tencent.mm.sdk.modelbase.BaseResp.ErrCode.ERR_OK;


/**
 * Created by xiaoke.ni on 2017/6/23.
 */

public class PayActivity extends AppCompatActivity implements View.OnClickListener,IWXAPIEventHandler {
    private RelativeLayout mPayAlipayRl;
    private ImageView mImgAlipay;
    private TextView mAlipayTitle;
    private TextView mAlipayTitleSub;
    private RelativeLayout mPayWechatRl;
    private ImageView mImgWechat;
    private TextView mWechatTitle;
    private TextView mWechatTitleSub;
    private RelativeLayout mPayCardRl;
    private ImageView mImgCard;
    private TextView mCardTitle;
    private TextView mCardTitleSub;

    private PayUtil payUtil;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pay);
        assignViews();
        initData();
    }

    private void initData() {
        payUtil = new PayUtil(this);
    }

    private void assignViews() {
        mPayAlipayRl = (RelativeLayout) findViewById(R.id.pay_alipay_rl);
        mImgAlipay = (ImageView) findViewById(R.id.img_alipay);
        mAlipayTitle = (TextView) findViewById(R.id.alipay_title);
        mAlipayTitleSub = (TextView) findViewById(R.id.alipay_title_sub);
        mPayWechatRl = (RelativeLayout) findViewById(R.id.pay_wechat_rl);
        mImgWechat = (ImageView) findViewById(R.id.img_wechat);
        mWechatTitle = (TextView) findViewById(R.id.wechat_title);
        mWechatTitleSub = (TextView) findViewById(R.id.wechat_title_sub);
        mPayCardRl = (RelativeLayout) findViewById(R.id.pay_card_rl);
        mImgCard = (ImageView) findViewById(R.id.img_card);
        mCardTitle = (TextView) findViewById(R.id.card_title);
        mCardTitleSub = (TextView) findViewById(R.id.card_title_sub);

        mPayAlipayRl.setOnClickListener(this);
        mPayWechatRl.setOnClickListener(this);
        mPayCardRl.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        PayBean payBean;
        Random random;
        StringBuilder stringBuilder;
        switch (v.getId()) {
            case R.id.pay_alipay_rl:
                payBean = new PayBean();
                payBean.setAmount("0.01");
                payBean.setClientIp("12");
                payBean.setOpenId("11");
                payBean.setP2c(false);
                payBean.setPlatFormId("1310");
                payBean.setRegAppType("wx");
                payBean.setTitle("支付");
                random = new Random();
                stringBuilder = new StringBuilder();
                for(int i = 0;i < 21;i++){
                    int a = random.nextInt(10);
                    stringBuilder.append(a);
                }
                payBean.setTradeNo(stringBuilder.toString());
                payUtil.aliPay(payBean);
                break;
            case R.id.pay_wechat_rl:
                payBean = new PayBean();
                payBean.setAmount("0.01");
                payBean.setClientIp("192.168.200.90");
                payBean.setOpenId("wxfbf6e942942b21cc");
                payBean.setP2c(false);
                payBean.setPlatFormId("1320");
                payBean.setRegAppType("QY");
                payBean.setTitle("支付");
                random = new Random();
                stringBuilder = new StringBuilder();
                for(int i = 0;i < 21;i++){
                    int a = random.nextInt(10);
                    stringBuilder.append(a);
                }
                payBean.setTradeNo(stringBuilder.toString());
                payUtil.WXpay(payBean);
                break;
            case R.id.pay_card_rl:
                payBean = new PayBean();
                payBean.setAmount("0.01");
                payBean.setClientIp("12");
                payBean.setOpenId("11");
                payBean.setP2c(false);
                payBean.setPlatFormId("1330");
                payBean.setRegAppType("wx");
                payBean.setTitle("支付");
                random = new Random();
                stringBuilder = new StringBuilder();
                for(int i = 0;i < 21;i++){
                    int a = random.nextInt(10);
                    stringBuilder.append(a);
                }
                payBean.setTradeNo(stringBuilder.toString());
                payUtil.unionPay(payBean);
                break;

        }
    }
/******************************** 银  联  *********************************/

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        /*************************************************
         * 步骤3：处理银联手机支付控件返回的支付结果
         ************************************************/
        if (data == null) {
            return;
        }

        String msg = "";
        /*
         * 支付控件返回字符串:success、fail、cancel 分别代表支付成功，支付失败，支付取消
         */
        String str = data.getExtras().getString("pay_result");
        if (str.equalsIgnoreCase("success")) {

            // 如果想对结果数据验签，可使用下面这段代码，但建议不验签，直接去商户后台查询交易结果
            // result_data结构见c）result_data参数说明

//            if (data.hasExtra("result_data")) {
//                String result = data.getExtras().getString("result_data");
//                try {
//                    JSONObject resultJson = new JSONObject(result);
//                    String sign = resultJson.getString("sign");
//                    String dataOrg = resultJson.getString("data");
//                    // 此处的verify建议送去商户后台做验签
//                    // 如要放在手机端验，则代码必须支持更新证书
//                    boolean ret = verify(dataOrg, sign, mMode);
//                    if (ret) {
//                        // 验签成功，显示支付结果
//                        msg = "支付成功！";
//                    } else {
//                        // 验签失败
//                        msg = "支付失败！";
//                    }
//                } catch (JSONException e) {
//                }
//            }
            // 结果result_data为成功时，去商户后台查询一下再展示成功
            msg = "支付成功！";
        } else if (str.equalsIgnoreCase("fail")) {
            msg = "支付失败！";
        } else if (str.equalsIgnoreCase("cancel")) {
            msg = "用户取消了支付";
        }

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("支付结果通知");
        builder.setMessage(msg);
        builder.setInverseBackgroundForced(true);
        // builder.setCustomTitle();
        builder.setNegativeButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.create().show();
    }

    @Override
    public void onReq(BaseReq baseReq) {

    }

    private IWXAPI api;
    @Override
    public void onResp(BaseResp resp) {
        ///第四步
        if (resp.getType() == ConstantsAPI.COMMAND_PAY_BY_WX) {
            if (resp.errCode == ERR_OK) {
                Toast.makeText(this,"微信支付成功",Toast.LENGTH_SHORT).show();
                return;
            } else if (resp.errCode == -1) {
                Toast.makeText(this,getResources().getString(R.string.app_fail_pay),Toast.LENGTH_SHORT).show();
            } else if (resp.errCode == -2) {
                Toast.makeText(this,getResources().getString(R.string.app_drop_pay),Toast.LENGTH_SHORT).show();
            }

        }
    }
}
